<script setup>
import { defineProps, ref, nextTick, onMounted, onBeforeUnmount } from 'vue';
import axios from 'axios';
import { ElButton, ElCard, ElDescriptions, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

const props = defineProps({
  orders: {
    type: Array,
    required: true
  },
});

const countdownTimers = ref({});
const canceledOrders = ref({});

onMounted(() => {
  props.orders.forEach(order => {
    if (order.status === 1) {
      startCountdown(order);
    }
  });
});

onBeforeUnmount(() => {
  Object.keys(countdownTimers.value).forEach(orderId => {
    const remainingTime = countdownTimers.value[orderId];
    localStorage.setItem(`countdown_${orderId}`, remainingTime);
  });
});

const cancel= (orderId) => {
  if (canceledOrders.value[orderId]) return;
  axios.post( `/productsOrders/cancel/${orderId}`).then(() => {
    const order = props.orders.find((order) => order.id === orderId);
    if (order) {
      order.status = 3;
    }
    canceledOrders.value[orderId] = true;
  });
};

const startCountdown = (order) => {
  const orderId = order.id;
  const now = Date.now();
  const orderTime = new Date(order.createdTime).getTime();
  const tenMinutesInMillis = 10 * 60 * 1000;
  const timePassed = now - orderTime;
  let remainingTime = tenMinutesInMillis - timePassed;

  if (remainingTime <= 0) {
    cancel(orderId);
    return;
  }

  const savedRemainingTime = localStorage.getItem(`countdown_${orderId}`);
  if (savedRemainingTime) {
    remainingTime = Math.min(remainingTime, parseInt(savedRemainingTime, 10));
  }

  countdownTimers.value[orderId] = remainingTime;

  const interval = setInterval(() => {
    countdownTimers.value[orderId] -= 1000;

    if (countdownTimers.value[orderId] <= 0) {
      clearInterval(interval);
      cancel(orderId);
    } else {
      localStorage.setItem(`countdown_${orderId}`, countdownTimers.value[orderId]);
    }
  }, 1000);
};

const formatCountdown = (time) => {
  if (time <= 0) return "0:00";
  const minutes = Math.floor(time / 60000);
  const seconds = Math.floor((time % 60000) / 1000);
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};

const payOrder = (orderId) => {
  const uniqueCode = generateUniqueCode();
  const orderIdStr = orderId.toString();
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: '正在跳转到支付页面...',
    spinner: 'el-icon-loading',
  });

  axios.post('/productsOrders/pay', { orderId: orderIdStr, uniqueCode })
      .then((resp) => {
        const divForm = document.getElementsByTagName('div');
        if (divForm.length) {
          document.body.removeChild(divForm[0]);
        }
        const div = document.createElement('div');
        div.innerHTML = resp.data;
        document.body.appendChild(div);
        document.forms[0].submit();
      })
      .catch((error) => {
        ElMessage.error(`订单: WNXY_CAR_${orderIdStr}，支付失败：${error.response.data}`);
      });
};

const cancelPurchase = (orderId) => {
  ElMessageBox.confirm('您确定要取消该商品订单吗？', '警告', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消',
    type: 'warning',
  }).then(() => {
    const token = localStorage.getItem('token');
    return axios.post(`/productsOrders/cancel/${orderId}`, {}, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
  }).then((response) => {
    ElMessage.success(response.data);
    const order = props.orders.find((order) => order.id === orderId);
    if (order) {
      order.status = 3; // 假设状态 3 表示已取消
    }
  }).catch((errorMsg) => {
    ElMessage({ type: 'info', message: errorMsg });
  });
};

const getOrderButtons = (status) => {
  switch (status) {
    case 1:
      return [
        { label: '去支付', type: 'primary', action: payOrder },
        { label: '取消订单', type: 'warning', action: cancelPurchase },
      ];
    case 2:
      return [
        { label: '删除订单', type: 'danger', action: cancelPurchase },
      ];
    case 3:
      return [
      ];
    default:
      return [];
  }
};

const toggleOrderDetails = (order) => {
  if (order.expanded) {
    order.expanded = false;
  } else {
    order.expanded = true;
    fetchOrderDetails(order);
  }
};

const fetchOrderDetails = async (order) => {
  try {
    const response = await axios.get(`/productsOrders/orders?orderId=${order.id}`);
    if (response.data && response.data.length > 0) {
      order.details = response.data[0];
    } else {
      order.details = {};
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败');
  }
};

const generateUniqueCode = () => {
  const timestamp = Date.now();
  const randomNum = Math.floor(Math.random() * 100000);
  return 'LBY' + timestamp + randomNum.toString().padStart(5, '0');
};

</script>

<template>
  <div v-for="order in orders" :key="order.id">
    <el-card class="order-card-body">
      <el-descriptions title="订单详情" :column="2" label-width="120px">
        <el-descriptions-item label="订单编号：">{{ order.id }}</el-descriptions-item>
        <el-descriptions-item label="预付金额：">¥{{ order.price }}</el-descriptions-item>
        <el-descriptions-item label="下单时间：">{{ order.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="下单人姓名：">{{ order.name }}</el-descriptions-item>
        <el-descriptions-item label="下单人地址：">{{ order.address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话：">{{ order.telephone }}</el-descriptions-item>
      </el-descriptions>

      <el-button v-if="order.status === 1" size="small" type="text" style="color: red;">
        倒计时: {{ formatCountdown(countdownTimers[order.id]) }}
      </el-button>

      <el-button @click="toggleOrderDetails(order)" size="small" type="text">
        {{ order.expanded ? '收起详情' : '查看详情' }}
      </el-button>

      <div v-if="order.expanded" class="order-expanded-details">
        <el-descriptions v-if="order.details && order.details.carPrice" title="详细信息" column="2" label-width="120px">
          <el-descriptions-item label="车辆总价：">¥{{ order.details.carPrice }}</el-descriptions-item>
          <el-descriptions-item label="车辆颜色：">{{ order.details.carColor }}</el-descriptions-item>
          <el-descriptions-item label="车轮胎：">{{ order.details.carWheel }}</el-descriptions-item>
          <el-descriptions-item label="车座椅：">{{ order.details.carSeat }}</el-descriptions-item>
          <el-descriptions-item label="车辆图片：">
            <img v-if="order.details.imgs" :src="order.details.imgs" alt="车辆图片" class="el-image">
            <span v-else>暂无图片</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="order-footer">
        <el-button
            v-for="button in getOrderButtons(order.status)"
            :key="button.label"
            size="small"
            round
            :type="button.type"
            :icon="button.icon"
            @click="() => button.action(order.id)"
        >
          {{ button.label }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.order-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
}

.order-card-body {
  padding: 20px;
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.order-footer {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}

.el-table-column {
  text-align: center;
}

.el-image {
  margin: 0 auto;
  display: block;
}

.el-button {
  padding: 6px 16px;
}

@media (max-width: 768px) {
  .order-container {
    padding: 10px;
  }

  .order-card {
    padding: 10px;
  }

  .order-footer {
    flex-direction: column;
  }

  .el-button {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>
